<template>
  <div class="app-container">
    <eHeader :param-bean="paramBean" :sup_this="sup_this" />
    <eForm ref="form" :sup_this="sup_this" />
    <el-row :gutter="15">
      <!--角色管理-->
      <el-col :span="12">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span class="role-span">角色列表</span>
            <div id="opt" style="float: right">
              <el-radio-group v-model="opt" size="mini">
                <el-radio-button label="userRadio">用户分配</el-radio-button>
                <el-radio-button label="menuRadio">菜单权限分配</el-radio-button>
                <el-radio-button label="orgsetRadio">组织分配</el-radio-button>
                <el-radio-button label="formRadio">业务表单分配</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <DataGridTable
            v-loading="loading"
            ref="mainTable"
            :sup_this="sup_this"
            :data="data.rtnList"
            :total="total"
            @selection-change="handleGridSelectionChange"
            @current-change="handleCurrentChange">
            <el-table-column prop="roleName" label="名称">
              <template slot-scope="scope">
                <edit :data="scope.row" :sup_this="sup_this" />
              </template>
            </el-table-column>
            <el-table-column :show-overflow-tooltip="true" prop="rmk" label="描述"/>
            <el-table-column :show-overflow-tooltip="true" prop="createDate" label="创建日期">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createDate) }}</span>
              </template>
            </el-table-column>
          </DataGridTable>
        </el-card>
      </el-col>
      <!-- 授权 -->
      <el-col :span="12">
        <el-card v-show="opt === 'userRadio'" class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定角色分配用户" placement="top">
              <span class="role-span">用户分配</span>
            </el-tooltip>
            <el-button
              v-permission="['SYS_ADMIN','COMMON_ADMIN','ROLE_ALL','ROLE_CREATE']"
              :disabled="!showButton"
              :loading="userLoading"
              icon="el-icon-check"
              size="mini"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="addUser">选择用户</el-button>
            <userSelectList ref="userSelectList" @userSelectCallback="userSelectCallback" />
          </div>
          <roleUserList v-show="currentId != '' " ref="roleUserList" :sup_this="sup_this" />
        </el-card>
        <el-card v-show="opt === 'formRadio'" class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定角色分配业务申请表单" placement="top">
              <span class="role-span">业务申请表单分配</span>
            </el-tooltip>
            <el-button
              v-permission="['SYS_ADMIN','COMMON_ADMIN','ROLE_ALL','ROLE_CREATE']"
              :disabled="!showButton"
              :loading="formLoading"
              icon="el-icon-check"
              size="mini"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="addForm">选择表单</el-button>
            <formSetSelectList ref="formSetSelectList" :sup_this="sup_this" @formSelectCallback="formSelectCallback" />
          </div>
          <roleFormList v-show="currentId != '' " ref="roleFormList" :sup_this="sup_this" />
        </el-card>
        <el-card v-show="opt === 'menuRadio'" class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定角色分配菜单" placement="top">
              <el-link class="role-span" @click="toggleMenuTreeExpand">菜单权限分配 <i class="el-icon-more el-icon--right" /> </el-link>
            </el-tooltip>
            <el-checkbox v-model="menuCheckStrictly">关联选择</el-checkbox>
            <el-button
              v-permission="['SYS_ADMIN','COMMON_ADMIN','ROLE_ALL','ROLE_CREATE']"
              :disabled="!showButton"
              :loading="menuLoading"
              icon="el-icon-check"
              size="mini"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="saveMenu">保存</el-button>
          </div>
          <el-tree
            ref="menu"
            :data="menus"
            :default-checked-keys="menuIds"
            :props="defaultProps"
            :check-strictly="!menuCheckStrictly"
            :default-expand-all="menuExpandAll"
            accordion
            show-checkbox
            node-key="id"/>
        </el-card>
        <el-card v-show="opt === 'orgsetRadio'" class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定角色分配组织" placement="top">
              <el-link class="role-span" @click="toggleOrgTreeExpand">组织权限分配 <i class="el-icon-more el-icon--right" /> </el-link>
            </el-tooltip>
            <el-checkbox v-model="orgCheckStrictly">关联选择</el-checkbox>
            <el-button
              v-permission="['SYS_ADMIN','COMMON_ADMIN','ROLE_ALL','ROLE_CREATE']"
              :disabled="!showButton"
              :loading="orgLoading"
              icon="el-icon-check"
              size="mini"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="saveOrg">保存</el-button>
          </div>
          <el-tree
            ref="org"
            :data="orgs"
            :default-checked-keys="orgIds"
            :props="defaultProps"
            :check-strictly="!orgCheckStrictly"
            :default-expand-all="orgExpandAll"
            show-checkbox
            accordion
            node-key="id"/>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import checkPermission from '@/utils/permission'
import { parseTime } from '@/utils/index'
import eHeader from './module/header'
import edit from './module/edit'
import eForm from './module/form'
import initData from '@/mixins/initData'
import { loadDataUrl } from '@/api/system/role'
import { getAllMenusTree } from '@/api/system/menu'
import { getOrgSetsByCpyCode } from '@/api/system/orgSet'
import { saveUser, saveMenu, saveOrg, saveRoleForm } from '@/api/system/role'
import roleUserList from './module/roleUserList'
import roleFormList from './module/roleFormList'
import userSelectList from '@/views/system/user/module/userSelectList'
import formSetSelectList from '@/views/system/form/formSet/module/formSetSelectList'

export default {
  components: { eHeader, edit, eForm, roleUserList, roleFormList, userSelectList, formSetSelectList },
  mixins: [initData],
  data() {
    return {
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      currentId: '',
      menuCheckStrictly: false, menuExpandAll: false,
      orgCheckStrictly: false, orgExpandAll: false,
      menuLoading: false, orgLoading: false, userLoading: false, formLoading: false,
      showButton: false, opt: 'menuRadio',
      delLoading: false, sup_this: this,
      menus: [], menuIds: [],
      orgs: [], orgIds: []
    }
  },
  created() {
    this.url = loadDataUrl()
    this.searchToggle = true
    this.getOrgs()
    this.getMenus()
    this.$nextTick(() => {
      this.init()
    })
  },
  methods: {
    parseTime,
    checkPermission,
    beforeInit() {
      this.$refs.menu.setCheckedKeys([])
      this.showButton = false
      return true
    },
    afterInit(res) {
      this.currentId = ''
    },
    getMenus() {
      getAllMenusTree().then(res => {
        this.menus = res.data
      })
    },
    getOrgs() {
      getOrgSetsByCpyCode().then(res => {
        this.orgs = res.data
      })
    },
    handleCurrentChange(val) {
      const _this = this
      // 清空权限与菜单的选中
      _this.$refs.org.setCheckedKeys([])
      _this.$refs.menu.setCheckedKeys([])
      // 初始化
      _this.menuIds = []
      _this.orgIds = []
      _this.currentId = ''
      if (val) {
        // 保存当前的角色id
        _this.currentId = val.id
        // 点击后显示按钮
        _this.showButton = true
        // 菜单数据需要特殊处理
        const menus = val.roleMenuVOList
        menus.forEach(function(row, index) {
          _this.menuIds.push(row.menuId)
        })
        // 处理组织数据
        const orgs = val.roleOrgVOList
        orgs.forEach(function(row, index) {
          _this.orgIds.push(row.orgId)
        })
        // 处理用户与部门数据
        const _thisRole = _this.$refs.roleUserList
        _thisRole.roleId = _this.currentId
        _thisRole.loadData()

        const _thisForm = _this.$refs.roleFormList
        _thisForm.roleId = _this.currentId
        _thisForm.loadData()
      }
    },
    userSelectCallback(selectedRows, userSelectObj) {
      const data = { busMainData: { id: this.currentId, roleUserVOList: [] }}
      selectedRows.forEach(row => {
        const tmpMenu = { userId: row.id, userAccount: row.userAccount }
        data.busMainData.roleUserVOList.push(tmpMenu)
      })
      saveUser(data).then(res => {
        userSelectObj.cancel()
        userSelectObj.loading = false
        this.$refs.roleUserList.loadData()
      }).catch(err => {
        userSelectObj.loading = false
        console.log(err)
      })
    },
    addUser() {
      const _this = this.$refs.userSelectList
      _this.loadData()
      _this.dialog = true
    },
    formSelectCallback(selectedRows, formSelectObj) {
      const data = { busMainData: { id: this.currentId, roleFormVOList: [] }}
      selectedRows.forEach(row => {
        const tmpForm = { formCode: row.sysGenCode, formName: row.formName }
        data.busMainData.roleFormVOList.push(tmpForm)
      })
      saveRoleForm(data).then(res => {
        formSelectObj.cancel()
        formSelectObj.loading = false
        this.$refs.roleFormList.loadData()
      }).catch(err => {
        formSelectObj.loading = false
        console.log(err)
      })
    },
    addForm() {
      const _this = this.$refs.formSetSelectList
      _this.paramBean.formTypeList = ['OA']
      _this.init()
      _this.dialog = true
    },
    saveOrg() {
      this.orgLoading = true
      const data = { busMainData: { id: this.currentId, roleOrgVOList: [] }}
      this.$refs.org.getCheckedNodes().forEach(function(tmpNode, index) {
        const tmpMenu = { orgId: tmpNode.id, orgCode: tmpNode.orgCode }
        data.busMainData.roleOrgVOList.push(tmpMenu)
      })
      saveOrg(data).then(res => {
        this.orgLoading = false
        this.init()
        // this.update()
      }).catch(err => {
        this.orgLoading = false
        console.log(err)
      })
    },
    saveMenu() {
      this.menuLoading = true
      const data = { busMainData: { id: this.currentId, roleMenuVOList: [] }}
      this.$refs.menu.getCheckedNodes().forEach(function(tmpNode, index) {
        // if (!tmpNode.children) {
        const tmpMenu = { menuId: tmpNode.id }
        data.busMainData.roleMenuVOList.push(tmpMenu)
        // }
      })
      saveMenu(data).then(res => {
        this.menuLoading = false
        this.init()
      }).catch(err => {
        this.menuLoading = false
        console.log(err)
      })
    },
    toggleMenuTreeExpand() {
      const _this = this
      _this.menuExpandAll = !_this.menuExpandAll
      const treeNodes = _this.$refs.menu.store._getAllNodes()
      for (var i = 0; i < treeNodes.length; i++) {
        treeNodes[i].expanded = _this.menuExpandAll
      }
    },
    toggleOrgTreeExpand() {
      const _this = this
      _this.orgExpandAll = !_this.orgExpandAll
      const treeNodes = _this.$refs.org.store._getAllNodes()
      for (var i = 0; i < treeNodes.length; i++) {
        treeNodes[i].expanded = _this.orgExpandAll
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
  .role-span {
    font-weight: bold;color: #303133;
    font-size: 15px;
  }
</style>
